<template>
  <div class="criteria-table">
    
    
    <!-- 列设置 -->
    <div class="column-settings">
      <el-button 
        type="primary" 
        plain 
        size="small" 
        @click="handleEditColumns"
      >
        编辑列设置
      </el-button>
    </div>

    <div class="table-container">
      <table class="criteria-table-content">
        <thead>
          <tr>
            <th 
              v-for="(col, cidx) in modelValue.columns" 
              :key="col.id"
              :style="{ width: col.width }"
            >
              <div class="th-inner">
                <el-input
                  v-model="col.title"
                  size="small"
                  placeholder="列标题"
                  class="th-title-input"
                />
              </div>
            </th>
            <th style="width: 60px">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in modelValue.rows" :key="row.id">
            <td v-for="col in modelValue.columns" :key="col.id">
              <!-- 序号类型 -->
              <template v-if="col.type === 'number'">
                {{ row[col.id] || index + 1 }}
              </template>
              
              <!-- 文本类型 -->
              <template v-else-if="col.type === 'text'">
                <el-input 
                  v-model="row[col.id]" 
                  placeholder="可输入内容"
                />
              </template>
              
              <!-- 多行文本类型（按行编辑） -->
              <template v-else-if="col.type === 'textarea'">
                <div class="textarea-rows">
                  <div 
                    v-for="(line, li) in (Array.isArray(row[col.id]) ? row[col.id] : (row[col.id] ? [row[col.id]] : ['']))" 
                    :key="li"
                    class="textarea-row"
                  >
                    <el-input
                      class="line-input"
                      type="textarea"
                      :rows="1"
                      :autosize="{ minRows: 1, maxRows: 1 }"
                      v-model="(row[col.id] = Array.isArray(row[col.id]) ? row[col.id] : (row[col.id] ? [row[col.id]] : ['']))[li]"
                      placeholder="可输入内容"
                    />
                    <el-button 
                      link 
                      type="primary"
                      size="small"
                      class="line-action"
                      @click="addTextareaLine(row, col.id, li + 1)"
                    >
                      <el-icon><Plus /></el-icon>
                    </el-button>
                    <el-button 
                      link 
                      type="danger" 
                      size="small"
                      class="mini-delete-btn"
                      :disabled="(row[col.id] && row[col.id].length <= 1)"
                      @click="deleteTextareaLine(row, col.id, li)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
              
              
              
              <!-- 复选框类型 -->
              <template v-else-if="col.type === 'checkbox'">
                <!-- 画布展示，并支持按“行”删除该行的某个选项 -->
                <div class="checkbox-options readonly-options">
                  <div 
                    v-for="(opt, optIndex) in (row.options && row.options[col.id] ? row.options[col.id] : col.options)" 
                    :key="opt.value || opt.label || optIndex"
                    class="option-item readonly"
                  >
                    <span class="preview-checkbox">☐</span>
                    <span class="option-label">{{ opt.label }}</span>
                    <el-button 
                      class="mini-delete-btn"
                      link
                      type="danger"
                      size="small"
                      @click="deleteRowCheckboxOption(row, col, optIndex)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
            </td>
            <td>
              <el-button-group>
                <el-button 
                  link 
                  type="danger" 
                  size="small"
                  @click="handleDeleteRow(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-button-group>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="table-actions">
        <el-button 
          type="primary" 
          plain
          size="small"
          @click="handleAddRow"
        >
          添加行
        </el-button>
      </div>
    </div>
    

    <!-- 列设置对话框 -->
    <el-dialog
      v-model="columnSettingsVisible"
      title="列设置"
      width="600px"
    >
      <div class="column-settings-content">
        <div 
          v-for="(col, index) in editingColumns" 
          :key="col.id"
          class="column-setting-item"
        >
          <div class="column-basic-settings">
            <el-input
              v-model="col.title"
              placeholder="列标题"
              class="column-title-input"
            />
            <el-select v-model="col.type" placeholder="选择类型" class="column-type-select">
              <el-option label="序号" value="number" />
              <el-option label="文本" value="text" />
              <el-option label="多行文本" value="textarea" />
              <el-option label="复选框" value="checkbox" />
            </el-select>
            <el-checkbox v-model="col.isBold">加粗</el-checkbox>
            <el-select v-model="col.fontSize" placeholder="字体大小" class="column-type-select">
              <el-option label="小二" value="小二" />
              <el-option label="小四" value="小四" />
              <el-option label="五号" value="五号" />
              <el-option label="小五" value="小五" />
            </el-select>
            <el-input-number
              v-model="col.widthCm"
              :min="0.25"
              :step="0.25"
              placeholder="宽度(cm)"
              class="column-width-input"
              controls-position="right"
            />
            <el-button-group>
              <el-button 
                link 
                type="primary" 
                :disabled="index === 0"
                @click="moveColumn(index, -1)"
              >
                <el-icon><ArrowUp /></el-icon>
              </el-button>
              <el-button 
                link 
                type="primary" 
                :disabled="index === editingColumns.length - 1"
                @click="moveColumn(index, 1)"
              >
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <el-button 
                link 
                type="danger"
                :disabled="editingColumns.length <= 1"
                @click="deleteColumn(index)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </div>
          
          <!-- 选项设置（复选框） -->
          <div 
            v-if="col.type === 'checkbox'"
            class="column-options-settings"
          >
            <div 
              v-for="(opt, optIndex) in col.options" 
              :key="opt.value"
              class="option-item"
            >
              <el-input
                v-model="opt.label"
                placeholder="选项文字"
                class="option-label-input"
              />
              <el-input
                v-model="opt.value"
                placeholder="选项值"
                class="option-value-input"
              />
              <el-button 
                link 
                type="danger"
                :disabled="col.options.length <= 1"
                @click="deleteOption(col, optIndex)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button 
              type="primary" 
              link
              @click="addOption(col)"
            >
              添加选项
            </el-button>
          </div>
        </div>
        
        <div class="column-settings-actions">
          <el-button 
            type="primary" 
            plain
            @click="addColumn"
          >
            添加列
          </el-button>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="columnSettingsVisible = false">取消</el-button>
          <el-button type="primary" @click="saveColumnSettings">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Delete, ArrowUp, ArrowDown, Plus } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  }
})
const sizeMap = { '小二': '18pt', '小四': '12pt', '五号': '10.5pt', '小五': '9pt' }

const getColInlineStyle = (col) => {
  const fontSize = sizeMap[col.fontSize] || sizeMap[props.modelValue.fontSize] || '10.5pt'
  const isBold = col.isBold ?? props.modelValue.isBold ?? false
  return { fontSize, fontWeight: isBold ? 'bold' : 'normal' }
}

const toggleColBold = (col) => {
  col.isBold = !col.isBold
  syncColumns()
}

const syncColumns = () => {
  // 目前仅本地更新，点击“确定”会统一保存；如需实时保存，可在此 emit 或调用持久化
}

// 发出更新事件（此组件内不再提供“居中/居左”按钮，改由右侧属性面板控制）
const emit = defineEmits(['update:modelValue'])

// 列设置相关
const columnSettingsVisible = ref(false)
const editingColumns = ref([])

// 将 width 字段转换为 cm（支持 px/cm/数字）
const widthToCm = (width, fallbackCm = 4) => {
  if (width === undefined || width === null) return fallbackCm;
  if (typeof width === 'number') return width; // 视为 cm
  const s = String(width).trim();
  if (s.endsWith('cm')) return parseFloat(s) || fallbackCm;
  if (s.endsWith('px')) return (parseFloat(s) || (fallbackCm * 40)) / 40;
  const n = parseFloat(s);
  return isNaN(n) ? fallbackCm : n; // 无单位则按 cm 处理
};

// 处理编辑列设置
const handleEditColumns = () => {
  editingColumns.value = JSON.parse(JSON.stringify(props.modelValue.columns)).map(col => {
    let cm;
    if (col.widthCm !== undefined && col.widthCm !== null && col.widthCm !== '') {
      cm = Number(col.widthCm) || (col.type === 'number' ? 0.75 : 4);
    } else if (col.type === 'number') {
      // 历史数据（px）忽略，统一给序号列一个更合理的默认 0.75cm
      cm = 0.75;
    } else {
      cm = widthToCm(col.width, 4);
    }
    return {
      ...col,
      isBold: col.isBold ?? false,
      fontSize: col.fontSize ?? '五号',
      widthCm: cm
    };
  });
  columnSettingsVisible.value = true;
}

// 添加列
const addColumn = () => {
  const newColumn = {
    id: `col_${Date.now()}`,
    title: '',
    type: 'text',
    width: '120px',
    widthCm: 4, // Default width in cm for text
    isBold: false,
    fontSize: '五号',
    options: []
  }
  editingColumns.value.push(newColumn)
}

// 移动列
const moveColumn = (index, direction) => {
  const newIndex = index + direction
  if (newIndex >= 0 && newIndex < editingColumns.value.length) {
    const temp = editingColumns.value[index]
    editingColumns.value[index] = editingColumns.value[newIndex]
    editingColumns.value[newIndex] = temp
  }
}

// 删除列
const deleteColumn = (index) => {
  editingColumns.value.splice(index, 1)
}

// 添加选项
const addOption = (column) => {
  if (!column.options) {
    column.options = []
  }
  column.options.push({
    label: `选项${column.options.length + 1}`,
    value: `option_${Date.now()}`
  })
}

// 删除选项
const deleteOption = (column, index) => {
  column.options.splice(index, 1)
}

// 保存列设置
const saveColumnSettings = () => {
  props.modelValue.columns = JSON.parse(JSON.stringify(editingColumns.value)).map(col => ({
    ...col,
    // 保存时将 cm 同步为字符串 cm，便于后端精确识别
    width: `${col.widthCm * 40}px`,
    widthCm: Number(col.widthCm)
  }));
  // 更新现有行的数据结构
  props.modelValue.rows.forEach(row => {
    editingColumns.value.forEach(col => {
      if (col.type === 'checkbox' && !row[col.id]) {
        row[col.id] = []
      }
      if (col.type === 'textarea') {
        if (!Array.isArray(row[col.id])) {
          row[col.id] = row[col.id] ? [String(row[col.id])] : ['']
        }
      }
      // 清理遗留的单选值与选项
      if (col.type !== 'checkbox') {
        if (Array.isArray(row.options?.[col.id])) {
          delete row.options[col.id]
        }
      }
    })
  })
  columnSettingsVisible.value = false
}

// 处理添加行
const handleAddRow = () => {
  if (!props.modelValue.rows) {
    props.modelValue.rows = []
  }
  const newRow = {
    id: Date.now(),
    options: {}
  }
  // 初始化每列的值和选项
  props.modelValue.columns.forEach(col => {
    if (col.type === 'checkbox') {
      newRow[col.id] = []
    } else if (col.type === 'radio') {
      newRow[col.id] = '';
      // 每一行都有一份独立的选项副本
      newRow.options[col.id] = JSON.parse(JSON.stringify(col.options || []));
    } else if (col.type === 'textarea') {
      newRow[col.id] = ['']
    } else {
      newRow[col.id] = col.type === 'number' ? props.modelValue.rows.length + 1 : ''
    }
  })
  props.modelValue.rows.push(newRow)
}

// 删除行内某个选项
const handleDeleteOption = (row, columnId, optionIndex) => {
  if (row.options && row.options[columnId]) {
    row.options[columnId].splice(optionIndex, 1);
  }
};

// 行内删除：仅删除当前行的该选项，不影响列默认配置
const deleteRowCheckboxOption = (row, column, optIndex) => {
  if (!row.options) row.options = {}
  if (!Array.isArray(row.options[column.id])) {
    // 首次在该行操作时，复制一份列的默认选项
    row.options[column.id] = JSON.parse(JSON.stringify(column.options || []))
  }
  row.options[column.id].splice(optIndex, 1)
}

// 画布内已不支持新增复选框选项（统一在“列设置”中操作）

// 处理删除表格行
const handleDeleteRow = (index) => {
  props.modelValue.rows.splice(index, 1)
  // 重新计算序号
  props.modelValue.rows.forEach((row, idx) => {
    props.modelValue.columns.forEach(col => {
      if (col.type === 'number') {
        row[col.id] = idx + 1
      }
    })
  })
}

// 文本域行操作
const addTextareaLine = (row, columnId, insertIndex) => {
  if (!Array.isArray(row[columnId])) {
    row[columnId] = row[columnId] ? [String(row[columnId])] : ['']
  }
  if (typeof insertIndex === 'number' && insertIndex >= 0 && insertIndex <= row[columnId].length) {
    row[columnId].splice(insertIndex, 0, '')
  } else {
    row[columnId].push('')
  }
}

const deleteTextareaLine = (row, columnId, index) => {
  if (!Array.isArray(row[columnId])) return
  if (row[columnId].length <= 1) return
  row[columnId].splice(index, 1)
}
</script>

<style lang="scss" scoped>
// 多行文本行样式
.textarea-rows {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.textarea-row {
  display: flex;
  align-items: center;
  gap: 6px;
}

.line-input {
  width: 60%; // 默认较短，避免一行过长；可根据表格列宽自然适配
}

.line-action {
  min-width: 24px;
}
.criteria-table {
  .table-title-input {
    margin-bottom: 16px;
  }
  
  .table-container {
    margin-bottom: 16px;
    overflow-x: auto;
  }
  
  .criteria-table-content {
    width: 100%;
    border-collapse: collapse;
    
    th, td {
      border: 1px solid #dcdfe6;
      padding: 8px 6px;
      text-align: center;
    }
    
    th {
      background-color: #f5f7fa;
      font-weight: bold;
    }
    
    .radio-group,
    .checkbox-group,
    .block-options {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 4px;
    }

    .radio-option {
      display: flex;
      align-items: center;
      gap: 4px;

      .delete-option-btn {
        visibility: hidden;
      }

      &:hover .delete-option-btn {
        visibility: visible;
      }
    }
  }
  
  .table-actions {
    margin-top: 16px;
    display: flex;
    justify-content: center;
  }
  
  .table-note-input {
    margin-top: 16px;
  }
}

// 画布中勾选项输入宽度
.option-label-input :deep(.el-input__wrapper){ padding: 0 6px; }

// 参照“竖向选项”风格的复选框列编辑样式
.styled-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
  display: grid;
  grid-template-columns: 1fr;
  gap: 6px;
  .option-item {
    display: grid;
    grid-template-columns: 16px 1fr 28px;
    align-items: center;
    column-gap: 6px;
    .checkbox-wrapper { width: 16px; height: 16px; display: flex; align-items: center; justify-content: center; }
    .checkbox { width: 14px; height: 14px; border: 1px solid #dcdfe6; border-radius: 2px; }
    .option-input :deep(.el-input__wrapper){ padding: 0 6px; }
  }
  .add-btn { justify-self: start; margin-left: 22px; }
}

.readonly-options {
  display: grid;
  grid-template-columns: 1fr;
  gap: 4px;
  .option-item.readonly { 
    display: grid; 
    grid-template-columns: 16px auto 24px; 
    align-items: center; 
    column-gap: 4px; 
    text-align: left; 
  }
}

.th-inner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}
.th-title-input :deep(.el-input__wrapper){ padding: 1px 6px; }

.column-settings {
  margin-bottom: 16px;
}

.column-settings-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 16px;
  
  .column-setting-item {
    margin-bottom: 24px;
    padding: 16px;
    border: 1px solid #eee;
    border-radius: 4px;
    
    .column-basic-settings {
      display: flex;
      gap: 8px;
      align-items: center;
      
      .column-title-input { width: 130px; }
      
      .column-type-select { width: 110px; }
      
      .column-width-input { width: 110px; }
    }
    
    .column-options-settings {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px dashed #eee;
      
      .option-item {
        display: flex;
        gap: 8px;
        align-items: center;
        margin-bottom: 8px;
        
        .option-label-input,
        .option-value-input {
          width: 150px;
        }
      }
    }
  }
  
  .column-settings-actions {
    display: flex;
    justify-content: center;
    margin-top: 16px;
  }
}

.preview-checkbox {
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  margin: 0 2px;
  font-family: sans-serif;
}

// 小型删除按钮与操作列保持一致
.mini-delete-btn :deep(.el-icon) { font-size: 14px; color: #f56c6c; }
.mini-delete-btn { padding: 0; }
</style> 